﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using Microsoft.SharePoint.Administration;
using ServBus.ListForm2010.Setup.Utilities;

namespace ServBus.ListForm2010.Setup.Commands
{
    class WaitingSolutionCmd : BaseCommand
    {
        public override string Description
        {
            get { return Properties.Resources.CmdWaiting; }
        }

        public bool AbortWaiting { get; set; }

        public WaitingSolutionCmd()
        {
            this.AbortWaiting = false;
        }

        private void RemoveJob()
        {
            foreach (SPJobDefinition job in SPFarm.Local.TimerService.JobDefinitions)
            {
                if (job.Title != null && job.Title.ToLower().Contains(Constants.WSPNAME.ToLower()))
                {
                    string jobName = job.Title;
                    job.Delete();
                    Log.WriteLog(Log.LogType.Info, jobName + " has been deleted.");
                }
            }
        }

        public override bool Execute()
        {
            try
            {
                //throw new Exception("waiting Error");
                Log.WriteLog(Log.LogType.Info, "Waiting for Job Complete...");
                SPSolution solution = SPFarm.Local.Solutions[Constants.WSPNAME];
                int secondsUsed = 0;
                while(true)
                {
                    if (!solution.JobExists)
                        break;
                    if(AbortWaiting)
                    {
                        Log.WriteLog(Log.LogType.Info, "User Aborted.");
                        return false;
                    }

                    secondsUsed++;
                    if (secondsUsed >= Constants.WAITING_SECONDS)
                    {
                        RemoveJob();
                        throw new Exception("Job Timeout.");
                    }
                    Thread.Sleep(1000);
                }
                Log.WriteLog(Log.LogType.Info, "Job Complete.");
                return true;
            }
            catch (Exception ex)
            {
                Log.WriteLog(Log.LogType.Error, "Waiting Error. " + ex.GetType().FullName + ". " + ex.Message);
                return false;
            }
        }

        public override bool Rollback()
        {
            return true;
        }
    }
}
